<?php
namespace wap\controllers;

use Yii;
use common\helps\api;
use yii\caching\ArrayCache;
use yii\web\ErrorAction;

/**
 * Site controller
 */
class OrderController extends CommonController
{
    //结算页
    public function actionIndex()
    {
        $user = $this->getCache('USER');

        $shop = array();
        if ($user['shop']) {
            foreach ($user['shop'] as $key => $sh) {
                $shop[] = array(
                    'value' => $key,
                    'label' => $sh['shopName'],
                    'id' => $sh['shopId'],
                    'info' => $sh['add'],
                );
            }
        }

        $goods = $this->getCartGoodsByShopId($shop[0]['id']);


        $param = [
            'shopId' => $shop[0]['id'],
            'list' => $goods
        ];
        $deliveryFee = api::post('bill/get-delivery-fee', $param);
        if ($deliveryFee['code'] == 200) {
            $deliveryFee = $deliveryFee['data']['deliveryFee1'] + $deliveryFee['data']['deliveryFee2'];
        } else {
            $deliveryFee = $deliveryFee['msg'];
        }

        return $this->render('index', ['deliveryFee' => $deliveryFee, 'goods' => $goods, 'shop' => json_encode($shop), 'shopType' => $user['shopType']]);
    }



    public function actionCheckShopLimit()
    {

        $data = Yii::$app->request->post();
        if (!isset($data['shopId']) || empty($data['shopId'])) {
            $this->retJson('请选择门店信息', 500);
        }

        $goods = $this->getCartGoodsByShopId($data['shopId']);

        if (!$goods) {
            $this->retJson('请先添加商品', 500,['请先添加商品']);
        }


        $param = [
            'shopId' => $data['shopId'],
            'list' => $goods
        ];


        $res = api::post('bill/check-shop-limit', $param);

        $this->retJson($res['msg'], $res['code'], $res['data']);
    }



    public function actionCartGoodsByShopId()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['shopId']) || empty($data['shopId'])) {
            $this->retJson('请选择门店信息', 500);
        }

        $goods = $this->getCartGoodsByShopId($data['shopId']);
        $param = [
            'shopId' => $data['shopId'],
            'list' => $goods
        ];
        $deliveryFee = api::post('bill/get-delivery-fee', $param);
        if ($deliveryFee['code'] == 200) {
            $deliveryFee = $deliveryFee['data']['deliveryFee1'] + $deliveryFee['data']['deliveryFee2'];
        } else {
            $deliveryFee = $deliveryFee['msg'];
        }
        $result = [
            'goods' => $goods,
            'deliveryFee' => $deliveryFee
        ];

        $this->retJson('', 200, $result);
    }


    private function getCartGoodsByShopId($shopId)
    {
        $param = array('shopId' => $shopId);
        $res = api::post('comm/get-warehouses-by-shop-id', $param);
        $goods = $this->getCache('ORDER_GOODS');


        $new_goods = array();
        if ($res['code'] == 200) {
            $warehouses = $res['data'];
            $waresouseIds = array_column($warehouses, 'id');
            foreach ($goods as $good) {
                if (in_array($good['warehouseId'], $waresouseIds)) {
                    $new_goods [] = $good;
                }
            }
        }
        return $new_goods;
    }


    //提交预定单
    public function actionSubmitPre()
    {

        $data = Yii::$app->request->post();
        if (!isset($data['shopId']) || empty($data['shopId'])) {
            $this->retJson('请选择门店信息', 500);
        }
        $user = $this->getCache('USER');
        $shopId = $data['shopId'];
        $userId = $user['userName'];
        $goods = $this->getCartGoodsByShopId($shopId);

        $param = array(
            'userId' => $userId,
            'shopId' => $shopId,
            'list' => $goods,
            'platform' => $data['platform']
        );
        $w = date("w");
        $time = date("H:i");

        if (!in_array($w, [1, 2, 3, 4, 5])) {
            $this->retJson('当前时间无法提交订单', 500);
        }

        if (!($time >= '00:00' && $time <= '15:45')) {
            $this->retJson('当前时间无法提交订单', 500);
        }


        $res = api::post('bill/add-pre-bill', $param);

        if ($res['code'] == 200) {
            //$this->delCache('ORDER_GOODS');

            if ($res['data']['billStatus'] != 1) {

                $this->retJson('无法支付,订单状态已改变', 500);
            }

            $paydata = [
                'platform' => $data['platform'],
                'orderId' => $res['data']['preBillNo'],
                'totalFee' => (int)($res['data']['payPrice'] * 100),
                'subject' => '汤家订货' . $res['data']['preBillNo'],
                'returnUrl' => Yii::$app->params['PAY_RETURN_URL']
            ];
            $pay_result = $this->http_pay($paydata);
            if ($pay_result['result'] && $pay_result['code'] == 0) {
                $this->retJson('订单创建成功', 200, $pay_result['data']);
            } else {
                $this->retJson($pay_result['message'], 500);
            }

        }
        $this->retJson($res['msg'], $res['code']);
    }


    //重新发起支付
    public function actionSubmitPreRe()
    {

        $w = date("w");
        $time = date("H:i");

        if (!in_array($w, [1, 2, 3, 4, 5])) {
            $this->retJson('当前时间无法支付订单', 500);
        }

        if (!($time >= '00:00' && $time <= '16:00')) {
            $this->retJson('当前时间无法支付订单', 500);
        }
        $data = Yii::$app->request->post();
        if (!isset($data['preBillNo']) || empty($data['preBillNo'])) {
            $this->retJson('订单号不存在', 500);
        }

        $res = api::post('bill/pre-bill', ['preBillNo' => $data['preBillNo']]);

        if ($res['code'] == 200) {
            $paydata = [
                'platform' => $res['data']['platform'],
                'orderId' => $res['data']['preBillNo'],
                'totalFee' => (int)($res['data']['payPrice'] * 100),
                'subject' => '汤家订货' . $res['data']['preBillNo'],
                'returnUrl' => Yii::$app->params['PAY_RETURN_URL']
            ];

            $pay_result = $this->http_pay($paydata);
            if ($pay_result['result'] && $pay_result['code'] == 0) {
                $this->retJson('订单创建成功', 200, $pay_result['data']);
            } else {
                $this->retJson($pay_result['message'], 500);
            }
        }
        $this->retJson($res['msg'], $res['code']);
    }


    public function actionCancelPre()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['preBillNo']) || empty($data['preBillNo'])) {
            $this->retJson('订单号不存在', 500);
        }

        $param = [
            'preBillNo' => $data['preBillNo']
        ];
        $res = api::post('bill/cancel-pre-bill', $param);
        $this->retJson($res['msg'], $res['code']);
    }


    public function actionPreDtl()
    {
        $data = Yii::$app->request->get();
        if (!isset($data['merOrderId']) && !isset($data['orderId'])) {
            return $this->redirect('/');
        }
        if (isset($data['orderId'])) {
            $orderId = $data['orderId'];
        } else {
            $orderId = substr($data['merOrderId'], 4);
        }

        $billpre = null;
        $res = api::post('bill/pre-bill', ['preBillNo' => $orderId]);
        $bill = $res['code'] == 200 ? $res['data'] : array();
        if (isset($bill['billNo']) && !empty($bill['billNo'])) {
            $bill['billNos'] = explode(',', $bill['billNo']);
        }
        return $this->render('predetail', ['bill' => $bill]);
    }


    /**
     * 调起支付
     * @param null $data
     * @return array|mixed|null|string
     */
    private function http_pay($data = null)
    {
        $data = $data ? http_build_query($data) : null;
        $url = Yii::$app->params['PAY_URL'];
        $postUrl = $url;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        if ($data) {
            $data = json_decode($data, 1);
        } else {
            $data = array('msg' => '接口错误', 'code' => 500, 'data' => null);
        }
        return $data;
    }


    //提交订单
    public function actionSubmit()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['shopId']) || empty($data['shopId'])) {
            $this->retJson('请选择门店信息', 500);
        }

        $w = date("w");
        $time = date("H:i");

        if (!in_array($w, [1, 2, 3, 4, 5])) {
            $this->retJson('当前时间无法提交订单', 500);
        }

        if ($w == 5 && $time >= '16:00') {
            $this->retJson('当前时间无法提交订单', 500);
        }


        $user = $this->getCache('USER');
        $shopId = $data['shopId'];
        $userId = $user['userName'];
        $goods = $this->getCartGoodsByShopId($shopId);

        $param = array(
            'userId' => $userId,
            'shopId' => $shopId,
            'list' => $goods,
        );

        Yii::error($param);

        $res = api::post('bill/add-bill', $param);
        if ($res['code'] == 200) {
            $this->delCache('ORDER_GOODS');
        }
        $this->retJson($res['msg'], $res['code']);
    }


    //订单列表
    public function actionList()
    {
        $data = Yii::$app->request->get();
        $user = $this->getCache('USER');
        $status = isset($data['status']) ? $data['status'] : 0;


        if ($status == 100) {
            $param = array(
                'userId' => $user['userName'],
                'shopId' => $user['shopId'],
//                'status' => 1,
            );
            $res = api::post('bill/pre-list', $param);

        } else {
            $param = array(
                'userId' => $user['userName'],
                'shopId' => $user['shopId'],
                'status' => $status,
            );
            $res = api::post('bill/list', $param);
        }

        $list = $res['code'] == 200 ? $res['data'] : array();
        return $this->render('list', ['list' => $list, 'status' => $status, 'shopType' => $user['shopType']]);
    }

    //订单详情
    public function actionDtl()
    {
        $data = Yii::$app->request->get();
        $billNo = isset($data['billNo']) ? $data['billNo'] : '';
        $user = $this->getCache('USER');
        $param = array(
            'userId' => $user['userName'],
            'billNo' => $billNo,
        );
        $res = api::post('bill/detail', $param);
        $bill = $res['code'] == 200 ? $res['data'] : array();
        return $this->render('detail', ['bill' => $bill]);
    }


    //收货
    public function actionReceipt()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['billNo']) || !isset($data['list']) || !is_array($data['list'])) {
            $this->retJson('参数错误', 500);
        }
        $user = $this->getCache('USER');
        $param = array(
            'userId' => $user['userName'],
            'billNo' => $data['billNo'],
            'list' => $data['list'],
            'imgData' => isset($data['imgData']) ? $data['imgData'] : null,
        );
        $res = api::post('bill/receipt', $param);
        $this->retJson($res['msg'], $res['code']);
    }


    public function actionUploadImage()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['imgbase64'])) {
            $this->retJson('参数错误', 500);
        }

        $res = api::post('bill/upload-image', ['imgbase64' => $data['imgbase64']]);
        $this->retJson($res['msg'], $res['code'],$res['data']);
    }

}